package com.forekenow.Demo12.Exercise;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Tools {
    public void write(List<Student> list){
        try {
            //创建一个节点流
            FileWriter fw = new FileWriter("Student.txt");
            BufferedWriter bw = new BufferedWriter(fw);
            Iterator<Student> it = list.iterator();
            while (it.hasNext()){
                Student stu = it.next();
                String str = stu.getId()+"\t"+stu.getName()+"\t"+stu.getAge()+"\t"+stu.getCollage();
                bw.write(str);
                bw.newLine();
            }
//            for (int i = 0; i < list.size(); i++) {
//                String str = list.get(i).getId() + "\t"+ list.get(i).getName() + "\t"+ list.get(i).getAge() + "\t" + list.get(i).getCollage();
//                bw.write(str);
//                bw.newLine();
//            }
            //释放资源
            bw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public List read(String filename) {
        FileReader fr = null;
        BufferedReader br = null;
        ArrayList<Student> a = new ArrayList<>();
        try {
            fr = new FileReader(filename);
            //创建一个BufferedReader处理流
            br = new BufferedReader(fr);
            String s = br.readLine();
            //先读取源文件中的一行（String）
            //然后需要对字符串进行拆分 1001 tom 12 abc 会返回String[]
            //将返回数组中的数据以Student的方式保存起来·然后将这个对象保存到List集合中
            while (s!=null){
                String[] split = s.split("\t");
                Student student = new Student();
                student.setId(Integer.parseInt(split[0]));
                student.setName(split[1]);
                student.setAge(Integer.parseInt(split[2]));
                student.setCollage(split[3]);
                a.add(student);
                System.out.println();
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //返回新的集合
        return null;
    }
}
